<template>
  <a-modal
    :open="props.modelVisible"
    title="分配详情"
    :width="'850px'"
    @cancel="emit('update:modelVisible', false)"
  >
    <template #footer>
      <a-popconfirm
        placement="left"
        :title="'是否要删除?'"
        ok-text="删除"
        cancel-text="取消"
        @confirm="deleteAssignment"
      >
        <a-button v-if="permission" type="primary" danger>删除</a-button>
      </a-popconfirm>
      <a-button @click="updateAssignmentEndTimeAndMember">确认</a-button>
    </template>
    <a-descriptions bordered>
      <a-descriptions-item label="分配状态" :span="1">
        <a-badge v-if="new Date() > props.assignment?.endTime" status="error" text="超时" />
        <a-divider v-if="new Date() > props.assignment?.endTime" type="vertical"></a-divider>
        <a-badge v-if="props.assignment?.assignmentStatus == 0" status="default" text="待领取" />
        <a-badge
          v-else-if="props.assignment?.assignmentStatus == 1"
          status="Processing"
          text="进行中"
        />
        <a-badge
          v-else-if="props.assignment?.assignmentStatus == 2"
          status="warning"
          text="待验收"
        />
        <a-badge
          v-else-if="props.assignment?.assignmentStatus == 3"
          status="Success"
          text="已完成"
        />
      </a-descriptions-item>
      <a-descriptions-item label="截至时间" :span="2">
        <a-date-picker
          v-model:value="selectedEndTime"
          style="width: 100%"
          :disabled="!permission"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          :allowClear="false"
        />
      </a-descriptions-item>

      <a-descriptions-item label="领取时间" :span="1">
        <div style="padding: 4px 11px">
          {{
            props.assignment?.startTime
              ? dayjs(props.assignment?.startTime).format('YYYY-MM-DD HH:mm:ss')
              : ''
          }}
        </div>
      </a-descriptions-item>
      <a-descriptions-item label="完成时间" :span="2">
        <div style="padding: 4px 11px">
          {{
            props.assignment?.finishTime
              ? dayjs(props.assignment?.finishTime).format('YYYY-MM-DD HH:mm:ss')
              : ''
          }}
        </div>
      </a-descriptions-item>

      <a-descriptions-item label="分配小组" :span="1">
        <a-select
          v-model:value="selectedTeamId"
          placeholder="请选择承担小组"
          :field-names="{ value: 'teamId', label: 'teamName' }"
          :options="teamItems"
          :disabled="!permission"
          style="width: 200px"
          @change="changeMembers(selectedTeamId)"
        />
      </a-descriptions-item>
      <a-descriptions-item label="承担人员" :span="2">
        <a-select
          v-model:value="selectedUserIds"
          mode="multiple"
          placeholder="请选择承担对象"
          optionFilterProp="userName"
          :disabled="!permission"
          :field-names="{ value: 'userId', label: 'userName' }"
          :options="items"
          style="width: 200px"
        />
      </a-descriptions-item>

      <a-descriptions-item label="创建人" :span="1">
        <div style="padding: 4px 11px">
          {{ props.assignment?.creatorName }}
        </div>
      </a-descriptions-item>
      <a-descriptions-item label="创建时间" :span="2">
        <div style="padding: 4px 11px">
          {{ dayjs(props.assignment?.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </div>
      </a-descriptions-item>
    </a-descriptions>
  </a-modal>
</template>
<script lang="ts" setup>
import ProjectDao from '@/daos/project_dao';
import TaskDao from '@/daos/task_dao';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
const store = useStore();
const projectDao = new ProjectDao();
const taskDao = new TaskDao();
//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  assignment: {
    type: Object
  }
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);
//截至时间
const selectedEndTime = ref();

//选中的小组id
const selectedTeamId = ref();
//选中的用户Id列表
const selectedUserIds = ref([]);

//删除开放开关
const permission = ref<boolean>(true);

//全部的小组成员列表
const teamItems = ref([]);
//根据选中的小组id 获取对应的成员
const changeMembers = (teamId) => {
  selectedUserIds.value = [];
  items.value = teamItems.value.find((team) => team.teamId === teamId).userList;
};

//全部项目成员列表
const items = ref();
//查询项目成员
const findMember = () => {
  projectDao
    .findProjectTeamsAndMembersByProjectId(null, store.getters.courseId)
    .then((result) => {
      teamItems.value = result.data.data;
      items.value = teamItems.value.find(
        (team) => team.teamId === props.assignment.teamId
      ).userList;
    })
    .catch((error) => {
      console.error('findTeamsAndMembers 错误', error);
    });
};

//删除任务分配记录
const deleteAssignment = async () => {
  taskDao
    .deleteAssignmentByAssignmentId([props.assignment?.assignmentId])
    .then((result) => {
      if (result.data.code === 200) {
        message.success(result.data.data);
        emit('update:modelVisible', false);
        emit('confirm');
      } else {
        message.error(result.data.code + ' : ' + result.data.msg);
      }
    })
    .catch((error) => {
      console.error('Error deleting assignment:', error);
    });
};
//修改详情内容
const updateAssignmentEndTimeAndMember = () => {
  if (selectedUserIds.value.length == 0) {
    message.error('承担人员不能为空');
  } else {
    taskDao
      .updateAssignmentEndTimeAndMember(
        props.assignment?.assignmentId,
        selectedEndTime.value,
        selectedTeamId.value,
        selectedUserIds.value
      )
      .then((result) => {
        message.success(result.data.data);
        emit('confirm');
      })
      .catch((error) => {
        console.error(
          '更新分配任务记录时间与成员失败 updateAssignmentEndTimeAndMember Error:',
          error
        );
      });
  }
};
//监听处理
watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue === true) {
      console.log(props.assignment);

      selectedEndTime.value = dayjs(props.assignment.endTime);
      selectedTeamId.value = props.assignment?.teamId;
      selectedUserIds.value = props.assignment?.userList.map((user) => user.userId);
      findMember();
    }
  }
);
</script>
